package com.oms.app.user.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oms.app.user.model.User;
import com.oms.app.user.service.IUserService;
import com.oms.base.OMSConfigHolder;
import com.oms.page.PageModel;
import com.oms.util.OMSFileUtils;


/**
 * 用户关联业务controller
 * @author Loong_Mit
 * @date Sep 1, 2012 12:35:52 PM
 */
@RequestMapping("")
public class UserAction {
	
	private IUserService userService;
	private Map<String, String> map = new HashMap<String, String>();
	private static final String jspRootPaht = OMSConfigHolder.getWebRoot().replaceAll("\\\\", "/") +  "jsp";
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	//绑定时间格式
	@InitBinder  
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true));
    }
	
	//跳转到登陆页面
	@RequestMapping(value="/user_login", method=RequestMethod.GET)
	public String login(HttpServletRequest request) {
		return "user/login";
	}
	
	//用户登陆
	@RequestMapping(value="/user_login", method=RequestMethod.POST)
	public String login(User userForm, HttpServletRequest request) {
		User user = userService.login(userForm);
		if ((userForm.getRegname().length() == 0) || (user == null)) {
			request.setAttribute("message", "用户名或密码错误，请检查！");
			return "user/login";
		}
		//获取用户资源
		//request.setAttribute("module", JSONObject.fromObject(new HashMap().put("list", list)));
		List list = null;
		if(user.getName().equals("admin")){
			list = userService.getAllModule();
		}else{
			//获取用户角色
			list = userService.getUserModule(user);
		}
		
		String shopid = userService.myShopId(user.getId())+"";
		
		System.out.println(" 2012年10月18日23:40:33 ： "+shopid);
		if(!"0".equals(shopid)){ // 店铺ID 不等于零
			for(int i=0;i<list.size();i++){
				Map mMap = (Map)list.get(i);
				mMap.put("ACTION", mMap.get("ACTION").toString().replaceAll("shopId",shopid));
			}
		}else{// 用户没有店铺
			for(int i=0;i<list.size();i++){
				Map mMap = (Map)list.get(i);
				System.out.println(list.size()+"--2012年10月19日0:21:52 ： -------------"+mMap.get("ACTION").toString()+"--"+(mMap.get("ACTION").toString().indexOf("shopId")>0));
				if(mMap.get("ACTION").toString().indexOf("shopId")>0){
					list.remove(mMap);
					i--;
				}
			}
		}

		request.getSession().setAttribute("modulelist",list);
		request.getSession().setAttribute("user", user);
		return "redirect:/user_my";
	}
	
	//退出登陆
	@RequestMapping("/user_logout")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute("user");
		return "redirect:/user_login";
	}
	
	//跳转到用户信息页面
	@RequestMapping(value="/user_my", method=RequestMethod.GET)
	public String my(HttpServletRequest request) {
		return "user/user_my";
	}
	
	@RequestMapping(value="/user_register", method=RequestMethod.GET)
	public String register() {
		return "user/register";
	}
	
	//用户注册
	@RequestMapping(value="/user_register", method=RequestMethod.POST)
	public String register(User registerForm, HttpServletRequest request) {
		if (userService.getUserByRegName(registerForm.getRegname()) != null) {
			request.setAttribute("message", "该用户名已注册！");
			return "user/register";
		}
		User user = userService.register(registerForm);
		request.setAttribute("message", "注册成功！");
		request.getSession().setAttribute("user", user);
		return "user/register";
	}
	
	//检测用户名是否存在
	@ResponseBody
	@RequestMapping(value="/user_exists", method=RequestMethod.POST)
	public String exists(@RequestParam("regname") String regName, HttpServletRequest request) {
		User user = userService.getUserByRegName(regName);
		return ((user == null) ? "1" : "0");
	}
	
	//跳转到验证码页面
	@RequestMapping(value="/checkCode/{time}", method=RequestMethod.GET)
	public String checkCode() {
		return "common/checkCode";
	}
	
	//检测验证码是否正确 这里采用validationEngine验证表单
	@ResponseBody
	@RequestMapping(value="/user_checkCode", method=RequestMethod.POST)
	public String checkCode(@RequestParam("check") String checkCode, HttpServletRequest request) {
		if (!checkCode.toUpperCase().equals(request.getSession().getAttribute("rand").toString().toUpperCase())) {
			return "0";
		} else {
			return "1";
		}
	}
	
	//跳转到用户修改个人信息页面
	@RequestMapping(value="/user_profile/{userId}", method=RequestMethod.GET)
	public String profile(@PathVariable String userId, HttpServletRequest request) {
		if (userId == null) {
			return "user/login";
		}
		User user = userService.getUserByPK(Integer.parseInt(userId));
		request.setAttribute("user", user);
		return "user/profile";
	}
	
	//用户修改个人信息保存
	@RequestMapping(value="/user_profileDo", method=RequestMethod.POST)
	public String profileDo(User userForm, HttpServletRequest request) {
		User user = userService.profile(userForm);
		request.getSession().setAttribute("user", user);
		request.setAttribute("message", "修改个人信息成功！");
		return "user/profile";
	}
	
	/********************************* 前端管理 BEGIN *********************************/
	//个人信息
	@RequestMapping(value="/user_frontIndex", method=RequestMethod.GET)
	public String frontIndex(HttpServletRequest request) {
		return "front/index";
	}
	/********************************* 前端管理 BEGIN *********************************/
	
	/********************************* 后台管理 BEGIN *********************************/
	//进入到商店管理页面
	@RequestMapping(value="/user_userManagerList")
	public String enterUserList(HttpServletRequest request) {
		return "manager/user/userManagerList";
	}
	//用户权限分配
	@RequestMapping(value="/user_setUserExtent")
	public String setUserExtent(HttpServletRequest request) {
		return "manager/user/setUserExtent";
	}
	//进入用户设置角色页面
	@RequestMapping(value="/user_userSetupRole/{userId}")
	public void userSetupRole(@PathVariable String userId,HttpServletRequest request,HttpServletResponse response) {
		//request.setAttribute("userId", userId);
		//return "manager/user/userSetupRole";
		try {
			PrintWriter out = response.getWriter();
			out.print(OMSFileUtils.readFileToString(new File(jspRootPaht+"/manager/user/userSetupRole.jsp"), "utf-8").replaceAll("\\{userId\\}", userId).replaceAll("\\{base\\}", "http://localhost:8080/OMS"));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	 // 用户设置角色
	@RequestMapping(value="/user_userAddRole/{userId}")
	public void userAddRole(@PathVariable String userId,HttpServletRequest request){

		String status = request.getParameter("status");
		map.put("roleid", request.getParameter("id"));
		map.put("userid", userId);
		
		if("true".equals(status)){
			//判断是否存在关联
			if(!userService.isUserRole(map)){
				userService.userAddRole(map);
			};
		}else{
			//判断是否存在关联
			if(userService.isUserRole(map)){
				//删除角色与模块（资源）关联关系
				userService.delUserRole(map);
			}
		}
		
	}
	//用户列表
	@ResponseBody
	@RequestMapping(value="/user_getUserList")
	public Map<String, Object> getUserList(HttpServletRequest request) {
		Map<String, Object> param = new HashMap<String, Object>();
		List<User> list = userService.getUserList(param);
		return PageModel.getListToString(list, request);
	}
	
	//删除用户
	@ResponseBody
	@RequestMapping(value="/user_delete/{userId}")
	public Map<String, Object> enterShopList(@PathVariable String userId, HttpServletRequest request) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (userService.deleteUser(Integer.parseInt(userId)) == 1) {
			json.put("success", true);
			json.put("message", "删除用户成功！");
		} else {
			json.put("success", false);
			json.put("message", "删除用户失败！");
		}
		return json;
	}
	
	//添加用户
	@ResponseBody
	@RequestMapping(value="/user_addUesr", method=RequestMethod.POST)
	public Map<String, Object> addUser(User registerForm, HttpServletRequest request) {
		Map<String, Object> json = new HashMap<String, Object>();
		if (userService.getUserByRegName(registerForm.getRegname()) != null) {
			json.put("success", false);
			json.put("message", "该用户名已注册！");
		}
		userService.register(registerForm);
		json.put("success", true);
		json.put("message", "添加用户成功！");
		return json;
	}
	
	//修改用户
	@ResponseBody
	@RequestMapping(value="/user_updateUser/{userId}", method=RequestMethod.POST)
	public Map<String, Object> updateUser(User userForm, @PathVariable String userId, HttpServletRequest request) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			User user = userService.getUserByRegName(userForm.getRegname());
			userForm.setId(Integer.valueOf(userId));
			userForm.setPassword(user.getPassword());
			userService.updateUser(userForm);
			json.put("success", true);
			json.put("message", "修改用户成功！");
			user = null;
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("message", "修改用户失败！");
		}
		return json;
	}
	/********************************* 后台管理 END *********************************/
	
}